package com.minggo.charmword.logic;

import java.util.Map;

import android.content.Context;
import android.os.AsyncTask;
import android.os.Handler;
import android.util.Log;

import com.google.gson.Gson;
import com.minggo.charmword.cache.CacheUtils;
import com.minggo.charmword.model.Result;
import com.minggo.charmword.model.User;
import com.minggo.charmword.net.ApiUrl;
import com.minggo.charmword.net.ApiUtil;
import com.minggo.charmword.util.UserUtil;

/**
 * 获取通告列表
 * 
 * @author minggo
 * @date 2014-3-14 下午8:55:35
 */
public class UserLoginUtil extends AsyncTask<Void, Void, User> {

	public static final int USER_LOGIN = 10000;
	private Handler handler;
	private User user;
	private Gson gson = new Gson();

	public UserLoginUtil(Context context, Handler handler, User user) {
		this.handler = handler;
		this.user = user;
	}

	@Override
	protected User doInBackground(Void... arg0) {

		String key = "user_info";
		/*
		 * String cacheContent = CacheUtils.getInstance().getDiskCache(key); if
		 * (!StringUtils.isEmpty(cacheContent)) { user =
		 * gson.fromJson(cacheContent, User.class); if (user!=null) {
		 * handler.obtainMessage(USER_LOGIN, user).sendToTarget(); } }
		 */
		Map<String, Object> params = ApiUtil.addRequiredParam();
		params.put("password", user.password);
		params.put("email", user.email);
		Result result = ApiUtil.getResult(ApiUrl.USER_LOGIN, params, false, null);
		if (null == result) {
			return null;
		}
		try {
			// Type listType = new TypeToken<List<Advice>>() {}.getType();
			User user = new Gson().fromJson(result.content, User.class);
			if (user != null) {
				Log.i("login", "username--->" + user.username);
				CacheUtils.getInstance().setDiskCache(key, gson.toJson(user));

				return user;
			}
		} catch (Exception e) {
			e.printStackTrace();
			// Log.e(PARSE_JSON, "获取用户信息 -->"+e.toString());
		}
		return null;
	}

	@Override
	protected void onPostExecute(User result) {
		super.onPostExecute(result);
		handler.obtainMessage(USER_LOGIN, result).sendToTarget();
	}

}
